<template>
  <div class="goodcart-container">
    <Head></Head>
    <div
      class="container"
      style="background-color: lightblue; margin-top: 10px"
    >
      <div
        v-if="goods.length === 0"
        style="
          margin: auto 10px;
          text-align: center;
          font-size: 32px;
          height: 200px;
          line-height: 200px;
          color: gray;
        "
      >
        购物车是空的～
      </div>
      <!-- 购物车中的商品 -->
      <!-- <div class="items" v-for="item in goods" :key="item.id" @click="goInfo"> -->
      <div class="items" v-for="item in goods" :key="item.id">
        <!-- <router-link to="/info"> -->
        <v-row>
          <v-col cols="1">
            <v-checkbox v-model="item.state" @click="select(item)">
            </v-checkbox>
            <!-- <v-checkbox v-model="item.state"> </v-checkbox> -->
          </v-col>
          <v-col cols="11">
            <v-row style="width: 500px; margin-top: 10px"
              ><v-select
                label="地址"
                v-model="item.addressBookId"
                :items="addressInfo"
                item-text="desp"
                item-value="id"
              ></v-select
            ></v-row>
            <v-row>
              <GoodItem
                :id="item.id"
                :image="item.image"
                :name="item.name"
                :price="item.price"
                :rand="item.rand"
                :sales="item.sales"
                :store="item.store"
                style="width: 500px"
              >
                <!-- <div class="counter">
              <button class="subtract">-</button>
              <p class="number">{{ item.counter }}</p>
              <button class="add">+</button>
            </div> -->
                <ul class="btn-numbox">
                  <li>
                    <ul class="count">
                      <li>
                        <span
                          id="num-jian"
                          class="num-jian"
                          @click.stop="subtract(item)"
                          >-</span
                        >
                      </li>
                      <li>
                        <input
                          type="text"
                          class="input-num"
                          id="input-num"
                          v-model="item.number"
                        />
                      </li>
                      <li>
                        <span
                          id="num-jia"
                          class="num-jia"
                          @click.stop="add(item)"
                          >+</span
                        >
                      </li>
                    </ul>
                  </li>
                </ul>
              </GoodItem>
            </v-row>
          </v-col>
        </v-row>
        <!-- </router-link> -->
      </div>
      <!-- 购物车中的商品 -->
      <hr />
      <!-- 底部结算 -->
      <v-row class="total">
        <v-col cols="4">
          <div style="">
            <v-checkbox
              v-model="fullState"
              label="全选"
              @change="fullChange"
            ></v-checkbox>
            <!-- <v-checkbox label="全选" @change="fullChange"></v-checkbox> -->
          </div>
        </v-col>
        <v-col cols="3">
          <div style="line-height: 67px; height: 67px; font-size: 20px">
            已选商品{{ totalNum }}件
          </div>
        </v-col>
        <v-col cols="3">
          <div style="line-height: 67px; height: 67px; font-size: 20px">
            共计{{ totalPrice }}元
          </div>
        </v-col>
        <v-col cols="2">
          <v-btn
            color="success"
            style="width: 90%; height: 100%; font-size: 32px"
            @click="submit"
            >结算</v-btn
          >
        </v-col>
      </v-row>
      <!-- 底部结算 -->
    </div>
    <div class="coupon-box" v-for="item in coupons" :key="item.id">
      <GoodCoupon
        :id="item.id"
        :money="item.value"
        :info="item.info"
        :name="item.name"
        :startTime="item.effectiveTime"
        :endTime="item.expirationTime"
      >
        <div @click="useCoupon(item)">
          {{ item.id === currentCoupon.id ? '已使用' : '未使用' }}
        </div>
      </GoodCoupon>
    </div>
  </div>
</template>

<script>
import Head from '@/components/Head.vue'
import GoodItem from '@/components/goods/GoodItem.vue'
import {
  getOrder,
  getOrderGoodList,
  deleteOrderGood,
  updateOrderGood,
  submitOrder,
  couponOrder
} from '@/api/order'
import { getAddressApi } from '@/api/address'
import { getCouponApi } from '@/api/coupon'
import GoodCoupon from '@/components/goods/GoodCoupon.vue'

import { payPath } from '@/utils/const'
// import { getGoodApi } from '@/api/home'
export default {
  components: {
    Head,
    GoodItem,
    GoodCoupon
  },
  data() {
    return {
      order: () => {},
      address: [],
      addressInfo: [],
      coupons: [],
      currentCoupon: () => {},
      goods: [
        // {
        //   id: 1,
        //   pic: require('@/assets/img/goog_1.jpeg'),
        //   name: '我是商品',
        //   price: 1,
        //   rand: 0,
        //   sales: 1300,
        //   sort: '111',
        //   counter: 1,
        //   state: false
        // },
        // {
        //   id: 2,
        //   pic: require('@/assets/img/goog_1.jpeg'),
        //   name: '我是商品',
        //   price: 2,
        //   rand: 0,
        //   sales: 1300,
        //   counter: 2,
        //   state: false
        // }
      ]
    }
  },
  computed: {
    fullState: {
      get() {
        // let fff = true
        // this.goods.forEach((good) => {
        //   if (good.state === false) fff = false
        // })
        // return fff
        return this.goods.every((item) => item.state)
      },
      set(val) {
        // console.log(val)
        return val
      }
      // setter
    },
    totalNum() {
      // console.log(this.goods)
      return this.goods
        .filter((item) => item.state)
        .reduce((total, item) => (total += item.number), 0)
    },
    totalPrice() {
      return this.goods
        .filter((item) => item.state)
        .reduce((total, item) => (total += item.number * item.price), 0)
    }
  },
  created() {
    this.init()
    this.getAddress()
  },
  // computed() {

  // },
  methods: {
    async useCoupon(item) {
      console.log(item)
      couponOrder({ id: this.order.id, couponId: item.coupon_id }).then(
        (res) => {
          this.currentCoupon = item
          console.log(res)
        }
      )
    },
    async getAddress() {
      await getAddressApi(sessionStorage.getItem('token')).then((response) => {
        console.log(response)
        this.address = response.data.data
        this.address.forEach((addr) => {
          let str = ''
          str +=
            addr.consignee +
            ' ' +
            addr.phone +
            ' ' +
            addr.tblArea[0].provinceName +
            ' ' +
            addr.tblArea[0].cityName +
            ' ' +
            addr.tblArea[0].district +
            ' ' +
            addr.detail
          addr.desp = str
          this.addressInfo.push(addr)
        })
        console.log(this.addressInfo)
      })
    },
    select(item) {
      // console.log(e)
      // item.state = !item.states
      // console.log(item)
    },
    submit() {
      const ppp = []
      this.goods.forEach((good) => {
        good.store -= good.number
        // console.log(good)
        let p
        if (good.state === false) {
          p = deleteOrderGood({ id: good.orderGoodId })
        } else {
          p = updateOrderGood({
            id: good.orderGoodId,
            addressBookId: good.addressBookId,
            number: good.number
          })
        }
        ppp.push(p)
      })
      Promise.all(ppp).then(() => {
        setTimeout(this.updateOrder(), 5000)
      })
    },
    async updateOrder() {
      await submitOrder({ id: this.order.id, status: 4 }).then((res) => {
        // console.log(res)
        // &subject=xxx&traceNo=xxx&totalAmount=xxx

        window.open(
          payPath +
            '?subject=' +
            'test' +
            '&traceNo=' +
            res.data.data +
            '&totalAmount=' +
            this.totalPrice,
          '_self'
        )

        // this.$router.push(payPath+'?subject='+'test'+'&traceNo=xxx&totalAmount=xxx')
      })
    },
    add(item) {
      if (item.number < item.store) {
        item.number++
        // item.store--
      } else item.number = item.store
      // console.log(this.goods)
      // this.totalPrice()
    },
    subtract(item) {
      if (item.number > 0) {
        item.number--
        // item.store++
      } else {
        item.number = 0
        item.state = false
      }
      // console.log(this.goods)
      // this.totalPrice()
    },
    async init() {
      const token = sessionStorage.getItem('token')
      await getOrder({ token, status: 1 }).then((res) => {
        this.order = res.data.data
        // console.log(this.order)
        this.currentCoupon.id = this.order.couponId
        this.getGoods()
      })
      // const token = sessionStorage.getItem('token')
      // console.log(token)
      await getCouponApi(token).then((res) => {
        // this.coupons = res.data.data
        // console.log(res)
      })
      // .then(() => {
      //   this.getGoods()
      // })
      // await getOrderGoodList(this.order.id).then((res) => {
      //   this.goods = res
      // })
    },
    async getGoods() {
      await getOrderGoodList({ orderId: this.order.id }).then((res) => {
        // console.log(res.data)
        this.goods = res.data.data
        this.goods.forEach((good) => {
          this.$set(good, 'state', true)
          // good.state = true
          good.store += good.number
          //       // const res = getGoodApi(good.goodId)
          //       // // console.log(res.data)
          //       // getGoodApi(good.goodId).then
          //       good = this.getGood(good)
        })
      })
      console.log(this.goods)
      //   // console.log('get')
      //   // console.log(this.order.id)
      //   console.log(this.goods)
    },
    // async getGood(good) {
    //   await getGoodApi(good.goodId).then((res) => {
    //     good = Object.assign(good, res.data.data)
    //     // console.log('good')
    //     // console.log(res)
    //     // console.log(good)
    //   })
    //   return good
    // },
    // goInfo() {
    //   this.$router.push('/info')
    // },
    test() {
      console.log(1)
    },
    fullChange(e) {
      // console.log(typeof e)
      // for (const i in this.goods) {
      //   console.log(i)
      // }
      this.goods.forEach((item) => {
        item.state = e
        // this.$set(item, 'state', e)
        // console.log(item)
        // (item.state = e)
      })
      // console.log(this.goods)
    }
    // comTotalNum() {
    //   this.totalNum = 0
    //   this.goods.forEach((item) => (this.totalNum += item.counter))
    //   console.log(this.totalNum)
    // }
  }
}
</script>

<style lang="less" scoped>
a {
  text-decoration: none;
  display: block;
  color: #333;
}
a:hover,
a:visited,
a:link,
a:active {
  color: #333;
}
.router-link-active {
  text-decoration: none;
  color: #333;
}
.items {
  font-size: 16px;
  .counter {
    float: left;
    display: block;
    border: #333 solid;
    p {
      display: inline-block;
      width: 50%;
      text-align: center;
      margin: 0;
      border: #333 0 solid;
    }
    button {
      display: inline-block;
      // margin: 5px;
      width: 20%;
    }
    // display: inline-block;
  }
}
.btn-numbox {
  overflow: hidden;
  // margin-top: 20px;
}

.btn-numbox li {
  float: left;
}

.btn-numbox .count {
  overflow: hidden;
  // margin: 0 16px 0 -20px;
}

.btn-numbox .count .num-jian,
.input-num,
.num-jia {
  display: inline-block;
  width: 28px;
  height: 28px;
  line-height: 28px;
  text-align: center;
  font-size: 18px;
  color: #999;
  cursor: pointer;
  border: 1px solid #e6e6e6;
}
.btn-numbox .count .input-num {
  width: 40px;
  height: 26px;
  color: #333;
  border-left: 0;
  border-right: 0;
}
label {
  margin-bottom: 0;
}
// .coupon-container {
//   display: block;
//   margin-left: 256px;
//   margin-top: 50px;
.coupon-box {
  display: inline-block;
  // width: 80%;
  margin-left: 50px;
  margin-bottom: 40px;
  margin-top: 100px;
}
// }
</style>
